home *** CD-ROM | disk | FTP | other *** search
Text File | 1990-05-04 | 2.9 KB | 128 lines | [TEXT/GEOL] |
- Item 2621463 30-April-90 15:34PDT
-
- From: D0532 Aidea Systems, Don Park,PRT
-
- To: CPLUS.DEV$ C++ Interest List--Developers
- CPLUS.APPLE$ C++ Interest List--Apple Employees
-
- Sub: Object Cache Macros
-
- I agree with you all about value parameter issue. To beg forgiveness for being
- wrong and thus providing evidence to those who claim that programmers are not
- deities, here is hack I wrote while back. It is a set of macro that allows
- objects to be cached.
-
- First, here is the header file. There is no implementation file.
-
- #ifndef__CACHE__
- #define__CACHE__
-
- #include <Generic.h> // name2() macro
-
- // Macro used to define name of cache class for given data type.
-
- #defineCache(TYPE) name2(CacheOf,TYPE)
- #defineCacheDeclare(TYPE) \
- class Cache(TYPE) \
- { \
- public: \
- static TYPE * \
- Get ( void ) \
- { \
- TYPE * dp; \
- if (dp = cache) \
- cache = *(TYPE**)dp; \
- return dp; \
- } \
- static void \
- Put ( TYPE * dp ) \
- { \
- *(TYPE**)dp = cache; \
- cache = dp; \
- } \
- private: \
- static TYPE * cache; \
- }
- #defineCacheImplement(TYPE) \
- TYPE * Cache(TYPE)::cache = 0L
-
- #endif __CACHE__
-
-
- Here is an usage example:
-
- #include <StdLib.h>
- #include <Stream.h>
- #include <Events.h>
- #include <Memory.h>
- #include "Cache.h"
-
- class IntObj;
-
- CacheDeclare(IntObj);
- CacheImplement(IntObj);
-
- class IntObj
- {
- public:
- void *
- operator new ( size_t sz )
- {
- void * dp;
-
- if (!(dp = Cache(IntObj)::Get()))
- dp = malloc(sz);
- return dp;
- }
- void
- operator delete ( void * dp )
- {
- Cache(IntObj)::Put((IntObj*)dp);
- }
- private:
- inti;
- };
-
- const NI = 100;
- const NJ = 100;
-
- IntObj * iobj[NJ];
-
- main ()
- {
- long tick;
- int i, j;
- void * dp;
-
- tick = TickCount();
-
- for (i = 0; i < NI; i++)
- {
- for (j = 0; j < NJ; j++)
- iobj[j] = new IntObj;
- for (j = 0; j < NJ; j++)
- delete iobj[j];
- }
- // Flush cached IntObj free store blocks
- while (dp = Cache(IntObj)::Get())
- free(dp);
-
- tick = TickCount() - tick;
- cout << "Cache Free Store = " << tick;
- return 0;
- }
-
- The reason I am sharing this with you guys is that this interesting set of
- macros allow very fast object allocation. Above example program will allocate
- and destroy 10,000 tiny objects in 7 to 8 ticks compared to over 100 ticks for
- not using it. While there are many different ways to implement caching in OOP,
- inheritance, reference, etc., use of separate class with static function
- members seems to be quite efficient and flexible to meet most requirements.
-
- Hope you enjoy them.
-
- Don Park
-
- P.S. Usage of malloc/free is not important to the scheme.
-
-